<?php
namespace Reseller\Model;

/**
 * 财务
 */
class FinanceModel extends BaseModel
{
    /**
     * 营业报表收入 显示通过审核的订单
     */
    public function report($where)
    {

        $m = M('line_orders as lo');
        //统计数据条数、实收成本need_pay、结算成本close_money、毛利
        $info = $m
            ->field('sum(end_need_pay), sum(need_pay), count(*)')
            ->where($where)
            ->find();
        $Page = new \Think\Page($info['count(*)'], 15); // 实例化分页类
        $show = $Page->show(); // 分页显示输出
        $list = $m
            ->field('lo.order_num,lo.total_num,
                need_pay,end_need_pay,lo.create_time,
                l.line_sn,l.line_name,lo.order_status,lo.create_time,manager_id,
                r.reseller_name')
            ->join('LEFT JOIN __PUBLIC_LINE__ as l on lo.line_id = l.line_id ')
            ->join('LEFT JOIN __OPERATOR_LINE_RESELLER__ as r on lo.sales_id = r.reseller_id ')
            ->where($where)
            ->order('lo.order_id desc')
            ->limit($Page->firstRow, $Page->listRows)
            ->select();
        $this->reportArrangeList($list);
        return ['list' => $list, 'show' => $show, 'info' => $info];
    }

    public function reportArrangeList(&$list){
        $pid = session('reseller_user.pid') ? session('reseller_user.pid') : session('reseller_user.reseller_id');
        $staff = D('Staff') -> getSomeStaff(['pid' => $pid], session('reseller_user.pid'));
        $staff = $this->changeIndex($staff);
        foreach ($list as $k => $v){
            $list[$k]['payee'] = $staff[$v['manager_id']]['reseller_name'];
        }
    }
    /**
     * 营业报表收入 导出
     */
    public function exportReportToExcel($where)
    {
        $list = M('line_orders as lo')
            ->field('lo.order_num,lo.total_num,
                need_pay,end_need_pay,lo.create_time,
                l.line_sn,l.line_name,lo.order_status,lo.create_time,
                r.reseller_name, manager_id')
            ->join('LEFT JOIN __PUBLIC_LINE__ as l on lo.line_id = l.line_id ')
            ->join('LEFT JOIN __OPERATOR_LINE_RESELLER__ as r on lo.sales_id = r.reseller_id ')
            ->where($where)
            ->order('lo.order_id desc')
            ->select();

        $pid = session('reseller_user.pid') ? session('reseller_user.pid') : session('reseller_user.reseller_id');
        $staff = D('Staff') -> getSomeStaff(['pid' => $pid], session('reseller_user.pid'));
        $staff = $this->changeIndex($staff);

        foreach ($list as $k => $v) {
            $list[$k]['order_num']   .= ' ';
            $list[$k]['profit']      = $v['end_need_pay'] - $v['need_pay'];
            $list[$k]['create_time'] = date('Y-m-d', $v['create_time']);
            $list[$k]['payee'] = $staff[$v['manager_id']]['reseller_name'];
        }

        $expCellName = array(
            array('order_num', '订单编号'),
            array('line_name', '线路名称'),
            array('total_num', '人数'),
            // array('order_status','订单状态'),
            array('end_need_pay', '实收'),
            array('need_pay', '成本'),
            ['payee', '收款人'],
            array('reseller_name', '销售员'),
            array('create_time', '下单时间'),
            array('profit', '毛利'),
        );

        $fileName = '营业收入报表';
        D('ExportExcel')->exportExcels($fileName, $expCellName, $list);

    }

    /**
     * 分销商财务结算订单退款
     */
    public function refuse()
    {
        $order_id = I('order_id');
        $m        = M('line_orders');
        //必须是审核不通过的订单才能退款
        if ($m->where(['order_id' => $order_id])->getField('order_status') != -2) {
            return ['status' => -2, 'msg' => '订单状态错误'];
        }

        $res = $m
            ->where(['order_id' => $order_id])
            ->data(['order_status' => -3])
            ->save();
        //返还位置

        if ($res !== false) {
            return ['status' => 1, 'msg' => '成功'];
        }

        return ['status' => -1, 'msg' => '失败'];
    }

    /**
     * 获取分销商结算列表
     */
    public function resellerList($where)
    {
        $m = M('line_orders as lo');

        //统计数据条数、实收成本end_need_pay、结算成本close_money、毛利
        $info = $m
            ->field('sum(need_pay), sum(end_need_pay), count(*)')
            ->where($where)
            ->find();

        $Page = new \Think\Page($info['count(*)'], 15); // 实例化分页类
        $show = $Page->show(); // 分页显示输出
        $list = $m
            ->field('lo.order_num,lo.order_id,lo.line_id,
                lo.adult_num,lo.child_num,lo.oldMan_num,
                end_need_pay,need_pay,
                l.line_sn,l.line_name,lo.order_status,lo.create_time,
                r.reseller_name')
            ->join('LEFT JOIN __PUBLIC_LINE__ as l on lo.line_id = l.line_id ')
            ->join('LEFT JOIN __OPERATOR_LINE_RESELLER__ as r on lo.sales_id = r.reseller_id ')
            ->where($where)
            ->order('lo.order_id desc')
            ->limit($Page->firstRow, $Page->listRows)
            ->select();
        return ['list' => $list, 'show' => $show, 'info' => $info];
    }

    /**
     * 获取发票列表
     */
    public function getBillList($where)
    {
        $order_type = session('reseller_user.shop_or_reseller');
        // 查询满足要求的总记录数
        $count = M('public_receipt')
            ->alias('r')
            ->field('receipt_id')
            //发票的分销商id等于店长的id
            ->join('inner JOIN ' . C('DB_PREFIX') . 'line_orders o ON o.order_id=r.order_id and o.manager_id = r.reseller_id and o.order_type=' . $order_type)
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'public_tourists t ON t.tourists_id=o.contact_id')
            ->where($where)
            ->count();
        // 分页
        $Page = new \Think\Page($count, 15); // 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show(); // 分页显示输出
        // 查询
        $list = M('public_receipt')
            ->alias('r')
            ->field('r.*,o.order_num,o.need_pay,l.line_name,t.tourists_phone,t.tourists_id')
            ->join('inner JOIN ' . C('DB_PREFIX') . 'line_orders o ON o.order_id=r.order_id and o.manager_id = r.reseller_id and o.order_type=' . $order_type)
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'public_tourists t ON t.tourists_id=o.contact_id')
            ->where($where)
            ->order('r.receipt_id desc')
            ->limit($Page->firstRow, $Page->listRows)
            ->select();

        return ['list' => $list, 'show' => $show];
    }

    /**
     * Excel导出发票列表-根据页面当前的筛选条件筛选
     */
    public function outBillListExportExcel($where)
    {
        $order_type = session('reseller_user.shop_or_reseller');
        $list       = M('public_receipt')
            ->alias('r')
            ->field('r.*,o.order_num,o.need_pay,l.line_name,t.tourists_phone,t.tourists_id')
            ->join('inner JOIN ' . C('DB_PREFIX') . 'line_orders o ON o.order_id=r.order_id and o.manager_id = r.reseller_id and o.order_type=' . $order_type)
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'public_line l ON l.line_id=o.line_id')
            ->join('LEFT JOIN ' . C('DB_PREFIX') . 'public_tourists t ON t.tourists_id=o.contact_id')
            ->where($where)
            ->order('r.receipt_id desc')
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['open_time'] = date('Y-m-d', $v['open_time']);
            $list[$k]['order_num'] .= ' ';
        }
        $expCellName = array(
            array('order_num', '订单号'),
            array('line_name', '线路名称'),
            array('need_pay', '销售价'),
            array('receipt_code', '发票代码'),
            array('receipt_num', '发票号码'),
            array('receipt_amount', '发票金额'),
            array('receipt_rise', '发票抬头'),
            array('receipt_content', '发票内容'),
            array('open_time', '开票时间'),
            array('open_user', '开据人'),
            array('remarks', '备注'),
        );

        $fileName = '发票统计表';
        D('Reseller/ExportExcel')->exportExcels($fileName, $expCellName, $list);
    }

    /**
     * Excel导出分销商结算列表-根据页面当前的筛选条件筛选
     * @param array $where where条件
     * @param int   $order_status 订单状态
     */
    public function outResellerSettlementListExportExcel($where, $order_status)
    {
        $list = M('line_orders as lo')
            ->field('lo.order_num,lo.adult_num,lo.child_num,lo.oldMan_num,
                need_pay,end_need_pay,l.line_sn,l.line_name,lo.create_time,r.reseller_name')
            ->join('LEFT JOIN __PUBLIC_LINE__ as l on lo.line_id = l.line_id ')
            ->join('LEFT JOIN __OPERATOR_LINE_RESELLER__ as r on lo.sales_id = r.reseller_id ')
            ->where($where)
            ->order('lo.order_id desc')
            // ->limit($Page->firstRow, $Page->listRows)
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['order_num'] .= ' ';
            $list[$k]['create_time'] = date('Y-m-d', $v['create_time']);
            $list[$k]['people_num']  = $v['adult_num'] . '/' . $v['child_num'] ;
            $list[$k]['profit']      = $v['end_need_pay'] - $v['need_pay'];
        }

        $expCellName = array(
            array('order_num', '订单编号'),
            array('line_sn', '线路编号'),
            array('line_name', '线路名称'),
            // array('order_status','订单状态'),
            array('create_time', '下单时间'),
            array('reseller_name', '销售人'),
            array('people_num', '收客人数(成/小)'),
            array('need_pay', '成本'),
            array('end_need_pay', '实收'),
            array('profit', '毛利'),
        );

        if ($order_status == 1) {
            $fileName = '财务结算(待审核)';
        } elseif ($order_status == 3) {
            $fileName = '财务结算(已审核)';
        } else {
            $fileName = '财务结算(审核不通过)';
        }

        D('ExportExcel')->exportExcels($fileName, $expCellName, $list);
    }
}
